package jp.shuitic.hatebwebhook.twitter.handler;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import jp.shuitic.hatebwebhook.twitter.web.client.HatebWebHookTwitUser;
import jp.shuitic.hatebwebhook.twitter.web.server.HatebWebHookTwitUserService;
import jp.shuitic.hatebwebhook.twitter.web.server.HatebWebHookTwitUserServiceImpl;

/**
 * Web HookでTwitterを更新する処理クラス
 * @author shuitic
 */
public class HatebHookExecuteImpl implements HatebHookExecute {

	static private HatebWebHookTwitUserService hwtUserService;
	static {
		hwtUserService = new HatebWebHookTwitUserServiceImpl();
	}

	@Override
	public void execute(String username, String key, String url, String title,
			String status, String timestamp, String comment, String isPrivate) throws Exception {
		HatebWebHookTwitUser hwtUser =  hwtUserService.findByHatebUserName(username);
		if (hwtUser == null) {
			return;
		}
		Twitter twitter = new Twitter(hwtUser.getTwitterUserName(), hwtUser.getTwitterPassword());
		try {
			if (twitter.verifyCredentials() != null) {
				StringBuffer msg = new StringBuffer();
				if (isEmpty(comment)) {
					msg.append(title);
				} else {
					msg.append(comment);
				}
				msg.append(" ");
				msg.append(url);
				twitter.setClientURL("http://hateb-hook-twit.appspot.com");
				twitter.setClientVersion("HatebTwit");
				twitter.updateStatus(msg.toString());
			}
		} catch (TwitterException e) {
			if (e.getStatusCode() == 401) {
				//Twitterのログインができない(Disableにしておく)
				hwtUser.setEnable(false);
				hwtUserService.save(hwtUser);
			} else {
				throw e;
			}
		}
	}
	private boolean isEmpty(String value) {
		return ((value == null) || value.equals(""));
	}

}
